package com.financing.wap.web.controller.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.financing.wap.common.BizEnums.CommonEnums;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.FpShopActivityUserDTO;
import com.financing.wap.dto.ShopperUserInfoDTO;
import com.financing.wap.service.IFpShopActivityUserService;
import com.financing.wap.service.IShopperUserInfoService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.HttpClientUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("userShopperVistCountController")
@RequestMapping("/api/userShopperVistCount")
public class UserShopperVistCountController extends BaseController{

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	IShopperUserInfoService shopperUserInfoService;

	@Autowired
	IFpShopActivityUserService fpShopActivityUserService;
	

	@Autowired
	private IUserService userService;

	/**
	 * 获取店铺排行榜排行
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/shopVistSort")
	@ResponseBody
	public ResultMap shopVistSort(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			logger.info("In  shopVistSort Begin!");
			//访问时间
			String vistDate=request.getParameter("vistDate");
			//limit 查询多少条
			String limitCount=request.getParameter("limitCount");

			if(StringUtil.isNullOrEmptyStr(limitCount)){
				limitCount="10";//默认查询10条
			}

			//默认没有时间限制
			String startDate="";
			String endDate="";
			String cjmd="";
			//限制时间
			if(!StringUtil.isNullOrEmptyStr(vistDate)){
				Map<String, String> readFile = readFile();
				startDate = URLEncoder.encode(readFile.get("incrementStartDate"),"utf-8");
				endDate = URLEncoder.encode(readFile.get("incrementEndDate"),"utf-8");
				//累积的需要过滤用户到达现场
				FpShopActivityUserDTO fpShopActivityUser=new FpShopActivityUserDTO();
				fpShopActivityUser.setDeleteTag(CommonEnums.DELETE_FLAG_1);
				List<FpShopActivityUserDTO> q = fpShopActivityUserService.queryList(fpShopActivityUser);
				StringBuffer sb=new StringBuffer();
				for (FpShopActivityUserDTO fpShopActivityUserDTO : q) {
					String mobile = fpShopActivityUserDTO.getMobile();
					sb.append(","+mobile);
				}
				if(sb.length()>0){
					cjmd=sb.substring(1).toString();
				}
			}
			if(StringUtil.isNullOrEmptyStr(startDate)){
				startDate=URLEncoder.encode("2017-10-13 00:00:00","utf-8");//默认在这之前
			}
			String url = mongodbUrl+shopVistSort;
			url = MessageFormat.format(url,startDate,endDate,limitCount,cjmd);
			logger.info("goto shopVistSort url: "+url);
			String res = HttpClientUtil.getInstance().doGetRequest(url);
			logger.info("get shopVistSort result:"+res);
			JSONObject jsonObj = JSONObject.fromObject(res);
			//添加产品销售状态
			JSONObject attributes = jsonObj.getJSONObject("attributes");
			Object o = attributes.get("list");
			JSONArray l = null;
			if(o instanceof JSONObject && ((JSONObject) o).isNullObject()){
				l = new JSONArray();
			}else{
				l = attributes.getJSONArray("list");
			}

			List<Map<String,Object>> list = JSONArray.toList(l, new HashMap<String,Object>(), new JsonConfig());

			//查询店铺名字
			for (Map<String, Object> map : list) {
				Object phone = map.get("shopId");
				ShopperUserInfoDTO shopperUserInfo=new ShopperUserInfoDTO();
				shopperUserInfo.setUserPhone(String.valueOf(phone));
				List<ShopperUserInfoDTO> gf = shopperUserInfoService.queryList(shopperUserInfo);
				if(gf.size()>0){
					ShopperUserInfoDTO shopperUserInfoDTO = gf.get(0);
					String shopperName = shopperUserInfoDTO.getShopperName();
					map.put("shopperName", shopperName);
					String userName = shopperUserInfoDTO.getUserName();
					map.put("userName", userName);
					//获取头像
					 getUserHeadImg(map, shopperUserInfoDTO);
				}else{
					map.put("shopperName", "理财师店铺");
					map.put("userHeadImg", CommonConstantUtil.DEFUALTIMAGE);
				}
				map.put("shopId", StringUtil.mobileHide4Number(String.valueOf(phone)));
			}

			result.setAttribute("list", list);
			result.setAttribute("className", UserShopperVistCountController.class.getName());
			result.setAttribute("methodName", "removenullvalue");
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info("In  shopVistSort end!");
		}catch(Exception e) {
			logger.error("get shopVistSort error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	private void getUserHeadImg(Map<String, Object> map,
			ShopperUserInfoDTO shopperUserInfoDTO) {
		FaUserDTO faUser = userService.getUserById(shopperUserInfoDTO.getUserId());
		 if(StringUtils.isNotBlank(shopperUserInfoDTO.getUserHeadImg())&&!shopperUserInfoDTO.getUserHeadImg().matches("/upload/faUser/image/\\d+.png")){
			 //自定义店铺头像优先级最高
			 map.put("userHeadImg",shopperUserInfoDTO.getUserHeadImg());
		 }else if(faUser.getFaUserWechatDTO() != null && StringUtils.isNotBlank(faUser.getFaUserWechatDTO().getHeadimgurl())){
			//微信头像第二
			 map.put("userHeadImg",faUser.getFaUserWechatDTO().getHeadimgurl());
		 }else {
			//默认头像
			 map.put("userHeadImg", CommonConstantUtil.DEFUALTIMAGE);
		 }
	}

	/**
	 * 获取单个用户店铺排行榜排行 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/shopUserVistSort")
	@ResponseBody
	public ResultMap shopUserVistSort(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			logger.info("In  shopUserVistSort Begin!");
			String shopId=request.getParameter("shopId");
			if(StringUtil.isNullOrEmptyStr(shopId)){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			JSONObject o = getVistCount(shopId, "");
			result.setAttribute("dto",JSON.parseObject(o.toString()));

			JSONObject lj = getVistCount(shopId, "true");
			result.setAttribute("zengliang",JSON.parseObject(lj.toString()));


			result.setAttribute("className", UserShopperVistCountController.class.getName());
			result.setAttribute("methodName", "removenullvalue");
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info("In  shopUserVistSort end!");
		}catch(Exception e) {
			logger.error("get shopUserVistSort error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	private JSONObject getVistCount(String shopId, String vistDate)
			throws UnsupportedEncodingException, SQLException {
		//默认没有时间限制
		String startDate="";
		String endDate="";
		String cjmd="";
		//限制时间
		if(!StringUtil.isNullOrEmptyStr(vistDate)){
			Map<String, String> readFile = readFile();
			startDate = URLEncoder.encode(readFile.get("incrementStartDate"),"utf-8");
			endDate = URLEncoder.encode(readFile.get("incrementEndDate"),"utf-8");
			//累积的需要过滤用户到达现场
			FpShopActivityUserDTO fpShopActivityUser=new FpShopActivityUserDTO();
			fpShopActivityUser.setDeleteTag(CommonEnums.DELETE_FLAG_1);
			List<FpShopActivityUserDTO> q = fpShopActivityUserService.queryList(fpShopActivityUser);
			StringBuffer sb=new StringBuffer();
			for (FpShopActivityUserDTO fpShopActivityUserDTO : q) {
				String mobile = fpShopActivityUserDTO.getMobile();
				sb.append(","+mobile);
			}
			if(sb.length()>0){
				cjmd=sb.substring(1).toString();
			}
		}
		if(StringUtil.isNullOrEmptyStr(startDate)){
			startDate=URLEncoder.encode("2017-10-13 00:00:00","utf-8");//默认在这之前
		}
		String url = mongodbUrl+shopUserVistSort;
		url = MessageFormat.format(url,shopId,startDate,endDate,cjmd);
		logger.info("goto shopUserVistSort url: "+url);
		String res = HttpClientUtil.getInstance().doGetRequest(url);
		logger.info("get shopUserVistSort result:"+res);
		JSONObject jsonObj = JSONObject.fromObject(res);
		//添加产品销售状态
		JSONObject attributes = jsonObj.getJSONObject("attributes");
		JSONObject o = attributes.getJSONObject("dto");

		ShopperUserInfoDTO shopperUserInfo=new ShopperUserInfoDTO();
		shopperUserInfo.setUserPhone(String.valueOf(shopId));
		List<ShopperUserInfoDTO> gf = shopperUserInfoService.queryList(shopperUserInfo);
		if(gf.size()>0){
			ShopperUserInfoDTO shopperUserInfoDTO = gf.get(0);
			String shopperName = shopperUserInfoDTO.getShopperName();
			o.put("shopperName", shopperName);
			o.put("shopperDesc", shopperUserInfoDTO.getShopperDesc());
			String userName = shopperUserInfoDTO.getUserName();
			o.put("userName", userName);
			//获取头像
			getUserHeadImg(o, shopperUserInfoDTO);
		}else{
			 o.put("shopperName", "理财师店铺");
			 o.put("userHeadImg", CommonConstantUtil.DEFUALTIMAGE);
		}
		o.put("shopId", StringUtil.mobileHide4Number(String.valueOf(shopId)));
		if(!StringUtil.isNullOrEmptyStr(cjmd)&&!cjmd.contains(shopId)){
			o.put("notInMd","true");
			try {
				Integer currentSort =(Integer) o.get("currentSort");
				o.put("currentSort", currentSort+1);
			} catch (Exception e) {
				logger.info("get currentSort +1 error",e);
			}
		}
		return o;
	}

	/**
	 * 获取活动时间
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getActivityTime")
	@ResponseBody
	public ResultMap getActivityTime(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			logger.info("In  getActivityTime Begin!");

			Map<String, String> readFile = readFile();
			String showTime = readFile.get("showTime");
			Date showTimeDate = DateUtil.format(showTime, "yyyy-MM-dd HH:mm:ss");
			if(showTimeDate.before(new Date())){
				readFile.put("isShowTime", "true");
			}

			result.setAttribute("dto", readFile);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info("In  getActivityTime end!");
		}catch(Exception e) {
			logger.error("get getActivityTime error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/***
	 * 读取文件
	 * @return
	 */
	public Map<String,String> readFile(){
		Map<String,String> result=new HashMap<String, String>();
		try {
			File file=new File("/disk/upload/time.txt");
			List<String> readLines = IOUtils.readLines(new FileInputStream(file));
			for (String obj : readLines) {
				if(!StringUtil.isNullOrEmptyStr(obj)){
					String[] s = obj.split("=");
					result.put(s[0],s[1]);
				}
			}
		} catch (Exception e) {
			logger.error("read time.txt error",e);
		}
		return result;
	}

	/** 放射 wap　过滤数据
	 * @param json
	 * @return
	 */
	public String wapremovenullvalue(String jsons){
		try {
			JSONObject json = JSONObject.fromObject(jsons);
			//获取  类名 方法名  进行放射
			JSONObject jo=json.getJSONObject("attributes");
			Object isList = jo.get("list");
			if(isList!=null){
				JSONArray list = jo.getJSONArray("list");
				//进行 多余字段过滤的数据
				for (int i = 0; i < list.size(); i++) {
					JSONObject jsonObject = list.getJSONObject(i);
					remove(jsonObject);
				}
			}else{
				JSONObject jsonObject=json.getJSONObject("dto");
				if(jsonObject!=null){
					remove(jsonObject);
				}
				try {
					Object jsonObject2 = json.get("zengliang");
					if(jsonObject2!=null){
						remove((JSONObject)jsonObject2);
					}
				} catch (Exception e) {
				}
			}
			return json.toString();
		} catch (Exception e) {
			log.error("error  wapshopperproduct:",e);
			return jsons;
		}
	}
	/***
	 * 删除垃圾空字段
	 * @param jsonObject
	 */
	private void remove(JSONObject jsonObject) {

		if(jsonObject.containsKey("host")){
			jsonObject.remove("host");
		}
		if(jsonObject.containsKey("param")){
			jsonObject.remove("param");
		}
		if(jsonObject.containsKey("wechatId")){
			jsonObject.remove("wechatId");
		}
		if(jsonObject.containsKey("type")){
			jsonObject.remove("type");
		}
		if(jsonObject.containsKey("activityId")){
			jsonObject.remove("activityId");
		}
		if(jsonObject.containsKey("otherJson")){
			jsonObject.remove("otherJson");
		}
		if(jsonObject.containsKey("referrer")){
			jsonObject.remove("referrer");
		}
		if(jsonObject.containsKey("source")){
			jsonObject.remove("source");
		}
		if(jsonObject.containsKey("path")){
			jsonObject.remove("path");
		}
		if(jsonObject.containsKey("createDate")){
			jsonObject.remove("createDate");
		}
		if(jsonObject.containsKey("productName")){
			jsonObject.remove("productName");
		}
		if(jsonObject.containsKey("referrerParam")){
			jsonObject.remove("referrerParam");
		}
		if(jsonObject.containsKey("loginName")){
			jsonObject.remove("loginName");
		}
		if(jsonObject.containsKey("viewCount")){
			jsonObject.remove("viewCount");
		}
		if(jsonObject.containsKey("queryTimes")){
			jsonObject.remove("queryTimes");
		}
		if(jsonObject.containsKey("monthStart")){
			jsonObject.remove("monthStart");
		}
		if(jsonObject.containsKey("monthEnd")){
			jsonObject.remove("monthEnd");
		}
		if(jsonObject.containsKey("cjmd")){
			jsonObject.remove("cjmd");
		}
	}

}
